package com.qlhx.timer;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.qlhx.common.VideoCallBackCache;
import com.qlhx.common.model.MQRegFace;
import com.qlhx.common.model.Result;
import com.qlhx.common.util.HTTP;
import com.qlhx.common.util.Img;
import com.qlhx.dao.BaseVisitorMapper;
import com.qlhx.model.BaseVisitor;
import com.qlhx.model.FaceModelInfo;
import com.qlhx.model.Wxuser;
import com.qlhx.model.bo.WxApplygoupBo;
import com.qlhx.mq.MQSender;
import com.qlhx.service.WechatPreapplygoupService;
import com.qlhx.wechat.common.util.HardWareUtils;
import io.micrometer.core.instrument.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.annotation.PropertySource;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.io.File;
import java.util.List;


/**
 * Create by byl
 *
 * @versio 1.0.0
 * @Author baiyanlong
 * @date 2019/7/4 15:54
 * @description desc: 微信预约同步接口
 */
@Lazy(false)
@Component
@EnableScheduling
@PropertySource("classpath:application-configs.properties")
public class TimerTask {
    @Autowired
    private WechatPreapplygoupService preapplygoupService;
    @Autowired
    private MQSender sender;
    @Autowired
    private RestTemplate res;
    @Autowired
    private BaseVisitorMapper baseVisitorMapper;
    Logger logger = LoggerFactory.getLogger(TimerTask.class);

    @Value("${syncwxyy.url}")
    private String syncwxyyurl;
    @Value("${syncwxyy.switch}")
    private boolean syncwxyyswitch ;
    @Value("${companycode}")
    public String companycode;// 公司标识编码
    @Value("${isopensenddata}")  //数据上传的开关
    private boolean  isOpenSendData;
    @Value("${imagePath}")
    private String imagePath;
    // 数据上传url
    @Value("${data.upload.url}")
    private String dataUploadUrl ;
    @Value("${imgPath}")
    private String imgPath;
    /**
     * 自动同步微信预约记录
     */
    @Scheduled(cron ="${syncapply.time}")
    private void syncwxyuyue() {
        if (syncwxyyswitch) {
            try {
                // 获取微信预约记录
                String maxWxYuYueTabTime = preapplygoupService.GetMaxWxYuYueTabTime();
                String time = "2001-01-01 00:00:00";
                if (!StringUtils.isBlank(maxWxYuYueTabTime)) {
                    time = maxWxYuYueTabTime;
                }
                String syncwxapplystr = HTTP.post(String.format("%s/sync/downWxApply?token="+ HardWareUtils.GetLocalAuthCode()+"&areaCode="+companycode, syncwxyyurl), "{\"companyCode\":\"" + companycode + "\",\"downTime\":\"" + time + "\"}");
                System.out.println("maxwxtime:" + time);
                System.out.println("获取微信预约记录：" + syncwxapplystr);
                if (syncwxapplystr != null) {// 获取未同步的微信用户列表
                    JSONObject json = JSONObject.parseObject(syncwxapplystr);
                    if (json.getIntValue("code") == 1000) {// 成功
                        // 将字符串转换成实体对象
                        List<WxApplygoupBo> bls = JSONArray.parseArray(
                                json.getString("content"), WxApplygoupBo.class);
                        try {
                            preapplygoupService.SyncWxApplyList(bls);

                        } catch (Exception e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    } else {
                        System.out.println("获取微信用户同步数据失败！");
                    }
                } else {
                    System.out.println("没有可同步的微信用户！");
                }
            } catch (Exception e) {
                logger.error("同步微信预约记录发生错误", e);
                e.printStackTrace();
            }
            finally {
            }
        } else {
            logger.info("没有开启同步微信用户开关 ！");
        }
    }


    /**
     * 同步头像
     */
    @Scheduled(cron ="${syncapply.time}")
    public synchronized void synwxHeadPhoto(){
        String format = String.format("%s/sync/getimages", syncwxyyurl);
        String syncwxapplystr = HTTP.post(format,null);
        if (syncwxapplystr != null) {// 获取未同步的微信用户列表
            JSONObject json = JSONObject.parseObject(syncwxapplystr);
            if (json.getIntValue("code") == 1000) {// 成功
                // 将字符串转换成实体对象
                String content = json.getString("content");
                List<Wxuser> wxusers = JSONArray.parseArray(content, Wxuser.class);
                try {
                    if (wxusers != null && wxusers.size() != 0) {  //存放同步过来的图片路径
                        String newfilepath =/* System.getProperty("rms").replace(
                                IConfig.get("pro"), IConfig.get("imgpro"))
                                +*/ imagePath+ File.separator;
                        for(Wxuser im : wxusers){
                            try {
                                Img.base642img(im.getPhoto(), imgPath+ File.separator+newfilepath+im.getPictureName());
                            }catch (Exception e){
                                e.printStackTrace();
                            }
                            if(im.getType() == 0){ //员工 直接注册
                                FaceModelInfo faceModelInfo = new FaceModelInfo();
                                faceModelInfo.setFacebasestr(Img.img2base64(imgPath+ File.separator+newfilepath+im.getPictureName()));
                                faceModelInfo.setUtype(1);
                                faceModelInfo.setUid(im.getUid().toString());
                                faceModelInfo.setIscompulsion(1);
                                faceModelInfo.setBindFaceYC(false);
                                Result result = new Result();
                                if(VideoCallBackCache.exists(faceModelInfo.getUid())){
                                    if(!VideoCallBackCache.get(faceModelInfo.getUid()).equals(im.getPictureName())){
                                        VideoCallBackCache.delSetByKey(faceModelInfo.getUid());
                                        VideoCallBackCache.set(faceModelInfo.getUid(),im.getPictureName());
                                        MQRegFace mQRegFace = new MQRegFace(null, im.getUname(), im.getCarNum(),
                                                newfilepath+im.getPictureName());
                                        sender.regFace(mQRegFace);
                                    }else{
                                        result.setCode(111);
                                        result.setContent("已有"+im.getUname()+"人脸。不进行注册");
                                    }
                                }else{
                                    VideoCallBackCache.set(faceModelInfo.getUid(),im.getPictureName());
                                    MQRegFace mQRegFace = new MQRegFace(null, im.getUname(), im.getCarNum(),
                                            newfilepath+im.getPictureName());
                                    sender.regFace(mQRegFace);
                                }
                                if(result.getCode() == 5000 || result.getCode() == 9000){
                                    logger.error("员工" + im.getUname() +"人脸 注册失败~");
                                }else{
                                    logger.info("员工" + im.getUname() +"人脸 "+result.getMsg());
                                }
                            }else{
                                BaseVisitor visitor = new BaseVisitor();
                                visitor.setPhone(im.getUtel());
                                visitor.setName(im.getUname());
                                BaseVisitor visitoInfo = res.postForObject("http://service-base/visitor/findVisitorByPhoneAndName", visitor, BaseVisitor.class);
                                if(visitoInfo != null) {
                                    BaseVisitor visitorInfo = new BaseVisitor();
                                    visitorInfo.setId(visitoInfo.getId());
                                    visitorInfo.setName(visitoInfo.getName());
                                    visitorInfo.setPhoto(Img.img2base64(imgPath+ File.separator+newfilepath + im.getPictureName()));
                                    FaceModelInfo faceModelInfo = new FaceModelInfo();
                                    faceModelInfo.setFacebasestr(Img.img2base64(imgPath+ File.separator+newfilepath+im.getPictureName()));
                                    faceModelInfo.setUtype(0);
                                    faceModelInfo.setUid(im.getUid().toString());
                                    faceModelInfo.setIscompulsion(1);
                                    faceModelInfo.setBindFaceYC(false);
                                    faceModelInfo.setVisitorInfo(visitorInfo);
                                    Result result = new Result();
                                    if(VideoCallBackCache.exists(faceModelInfo.getUid())){
                                        if(!VideoCallBackCache.get(faceModelInfo.getUid()).equals(im.getPictureName())){
                                            VideoCallBackCache.delSetByKey(faceModelInfo.getUid());
                                            VideoCallBackCache.set(faceModelInfo.getUid(),im.getPictureName());
                                            MQRegFace mQRegFace = new MQRegFace(null, im.getUname(), im.getCarNum(),
                                                    newfilepath+im.getPictureName());
                                            sender.regFace(mQRegFace);
                                        }else{
                                            result.setCode(111);
                                            result.setContent("已有"+im.getUname()+"人脸。不进行注册");
                                        }
                                    }else{
                                        VideoCallBackCache.set(faceModelInfo.getUid(),im.getPictureName());
                                        MQRegFace mQRegFace = new MQRegFace(null, im.getUname(), im.getCarNum(),
                                                newfilepath+im.getPictureName());
                                        sender.regFace(mQRegFace);
                                    }
                                    if(result.getCode() == 5000 || result.getCode() == 9000){
                                        logger.error("员工" + im.getUname() +"人脸 注册失败~");
                                    }else{
                                        logger.info("员工" + im.getUname() +"人脸 "+result.getMsg());
                                    }
                                }
                            }
                        }
                        logger.info("拉去头像信息成功~");
                    } else {
                        logger.info("拉去头像信息失败~");
                    }
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            } else {
                System.out.println("同步微信头像失败");
            }
        }
    }
}
